<template>
  <div class="menu-manage-root">
    <v-row>
      <v-col cols="12" md="4" class="pr-4">
        <v-card>
          <v-card-title>菜单树</v-card-title>
          <v-card-text>
            <TreeList
              :items="menuTree"
              :selected-id="selectedId"
              @select="onMenuNodeClick"
            />
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" md="8">
        <v-card>
          <v-card-title class="d-flex justify-space-between align-center">
            <span>菜单详情</span>
            <div>
              <v-btn color="primary" @click="showAddDialog = true">新增菜单</v-btn>
              <v-btn color="info" v-if="menuDetail" class="ml-2" @click="onEditMenu">编辑</v-btn>
              <v-btn color="error" v-if="menuDetail" class="ml-2" @click="onDeleteMenu">删除菜单</v-btn>
              <v-btn color="primary" v-if="menuDetail" class="ml-2" @click="openAssignRoleDialog">分配角色</v-btn>
            </div>
          </v-card-title>
          <v-card-text>
            <v-table v-if="menuDetail">
              <tbody>
                <tr><td><strong>菜单ID</strong></td><td>{{ menuDetail.menuId }}</td></tr>
                <tr><td><strong>菜单名</strong></td><td>{{ menuDetail.menuName }}</td></tr>
                <tr><td><strong>路径</strong></td><td>{{ menuDetail.path }}</td></tr>
                <tr><td><strong>组件</strong></td><td>{{ menuDetail.component }}</td></tr>
                <tr><td><strong>父级</strong></td><td>{{ menuDetail.parentId }}</td></tr>
                <tr><td><strong>图标</strong></td><td>{{ menuDetail.icon }}</td></tr>
                <tr><td><strong>权限</strong></td><td>{{ menuDetail.permission }}</td></tr>
                <tr><td><strong>排序</strong></td><td>{{ menuDetail.sort }}</td></tr>
                <tr><td><strong>状态</strong></td><td>{{ menuDetail.status === 1 ? '启用' : '停用' }}</td></tr>
              </tbody>
            </v-table>
            <div v-else>请选择左侧菜单查看详情</div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
    <!-- 新增菜单弹窗 -->
    <v-dialog v-model="showAddDialog" max-width="500px">
      <v-card>
        <v-card-title>新增菜单</v-card-title>
        <v-card-text>
          <v-form ref="addFormRef" @submit.prevent="onAddMenu">
            <v-text-field v-model="addForm.menuName" label="菜单名" required />
            <v-text-field v-model="addForm.path" label="路径" />
            <v-text-field v-model="addForm.component" label="组件" />
            <v-select
              v-model="addForm.parentId"
              :items="parentMenuOptions"
              item-title="menu_name"
              item-value="menu_id"
              label="父级菜单"
              clearable
            />
            <v-text-field v-model="addForm.icon" label="图标" />
            <v-text-field v-model="addForm.permission" label="权限" />
            <v-text-field v-model.number="addForm.sort" label="排序" type="number" />
            <v-select v-model="addForm.status" :items="statusOptions" label="状态" />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showAddDialog = false">取消</v-btn>
          <v-btn color="primary" @click="onAddMenu">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="showEditDialog" max-width="500px">
      <v-card>
        <v-card-title>编辑菜单</v-card-title>
        <v-card-text>
          <v-form ref="editFormRef" @submit.prevent="onUpdateMenu">
            <v-text-field v-model="editForm.menuName" label="菜单名" required />
            <v-text-field v-model="editForm.path" label="路径" />
            <v-text-field v-model="editForm.component" label="组件" />
            <v-select
              v-model="editForm.parentId"
              :items="parentMenuOptions"
              item-title="menu_name"
              item-value="menu_id"
              label="父级菜单"
              clearable
            />
            <v-text-field v-model="editForm.icon" label="图标" />
            <v-text-field v-model="editForm.permission" label="权限" />
            <v-text-field v-model.number="editForm.sort" label="排序" type="number" />
            <v-select v-model="editForm.status" :items="statusOptions" label="状态" />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showEditDialog = false">取消</v-btn>
          <v-btn color="primary" @click="onUpdateMenu">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="showDeleteDialog" max-width="400px">
      <v-card>
        <v-card-title>确认删除</v-card-title>
        <v-card-text>确定要删除该菜单吗？此操作不可恢复。</v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showDeleteDialog = false">取消</v-btn>
          <v-btn color="error" @click="confirmDeleteMenu">删除</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="assignRoleDialog" max-width="400px" persistent>
      <v-card>
        <v-card-title>分配角色</v-card-title>
        <v-card-text>
          <v-select
            v-model="selectedRoles"
            :items="allRoles"
            item-title="name"
            item-value="id"
            label="选择角色"
            multiple
            chips
            clearable
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="closeAssignRoleDialog">关闭</v-btn>
          <v-btn color="primary" @click="onSaveAssignRole">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import TreeList from './TreeList.vue'
import { getMenuTree, getMenuById, deleteMenu, updateMenu, getAllRoles, getRolesByMenuId, allocateMenuRoles } from '@/api/menu'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'

const menuTree = ref([])
const menuDetail = ref(null)
const selectedId = ref(null)
const showAddDialog = ref(false)
const showDeleteDialog = ref(false)
const showEditDialog = ref(false)
const assignRoleDialog = ref(false)
const addForm = ref({
  menuName: '',
  path: '',
  component: '',
  parentId: '',
  icon: '',
  permission: '',
  sort: 0,
  status: 1
})
const editForm = ref({})
const statusOptions = [
  { title: '启用', value: 1 },
  { title: '停用', value: 0 }
]
const allRoles = ref([])
const selectedRoles = ref([])

// 扁平化菜单树，获取所有菜单项
function flattenMenus(tree) {
  let arr = []
  for (const node of tree) {
    arr.push(node)
    if (node.children && node.children.length) {
      arr = arr.concat(flattenMenus(node.children))
    }
  }
  return arr
}

const parentMenuOptions = computed(() => [
  { menu_id: -1, menu_name: '目录' },
  ...flattenMenus(menuTree.value)
])

function fixTreeChildren(nodes) {
  if (!Array.isArray(nodes)) return []
  return nodes.map(node => ({
    ...node,
    children: fixTreeChildren(node.children || [])
  }))
}

function loadMenuTree() {
  getMenuTree().then(res => {
    const raw = res.data.data || []
    menuTree.value = fixTreeChildren(raw)
  })
}

function onMenuNodeClick(node) {
  selectedId.value = node.menu_id
  getMenuById(node.menu_id).then(res => {
    menuDetail.value = res.data.data || null
  })
}

function onAddMenu() {
  // 新增菜单接口 POST /actions/menuManageUrl/add
  axios.post(`${API_BASE_URL}/actions/menuManageUrl/add`, {
    menuName: addForm.value.menuName,
    path: addForm.value.path,
    component: addForm.value.component,
    parentId: addForm.value.parentId,
    icon: addForm.value.icon,
    permission: addForm.value.permission,
    sort: addForm.value.sort,
    status: addForm.value.status
  }).then(() => {
    showAddDialog.value = false
    loadMenuTree()
  })
}

function onEditMenu() {
  if (!menuDetail.value) return
  editForm.value = { ...menuDetail.value }
  showEditDialog.value = true
}

function onUpdateMenu() {
  updateMenu(editForm.value).then(() => {
    showEditDialog.value = false
    loadMenuTree()
    if (editForm.value.menuId) {
      getMenuById(editForm.value.menuId).then(res => {
        menuDetail.value = res.data.data || null
      })
    }
  })
}

function onDeleteMenu() {
  showDeleteDialog.value = true
}

function confirmDeleteMenu() {
  if (!menuDetail.value) return
  const  menuId = menuDetail.value.menuId
  deleteMenu(menuId).then(() => {
    console.log(menuDetail.value)
    showDeleteDialog.value = false
    menuDetail.value = null
    loadMenuTree()
  })
}

function openAssignRoleDialog() {
  if (!menuDetail.value) return
  assignRoleDialog.value = true
  getAllRoles().then(res => {
    allRoles.value = (res.data.list || []).map(role => ({
      ...role,
      id: String(role.id)
    }))
    getRolesByMenuId(menuDetail.value.menu_id).then(r => {
      let roles = r.data.data
      if (!Array.isArray(roles)) roles = roles ? [roles] : []
      selectedRoles.value = roles.map(role => String(role.id))
    })
  })
}

function closeAssignRoleDialog() {
  assignRoleDialog.value = false
  selectedRoles.value = []
}

function onSaveAssignRole() {
  if (!menuDetail.value) return
  allocateMenuRoles({
    menuId: menuDetail.value.menu_id,
    roleIds: selectedRoles.value.join(',')
  }).then(() => {
    closeAssignRoleDialog()
    // 可选：刷新详情或提示
  })
}

onMounted(() => {
  loadMenuTree()
})
</script>

<style scoped>
.menu-manage-root {
  padding: 32px;
  font-size: 18px;
}
.v-card {
  margin-bottom: 16px;
}
</style>
